package org.springframework.session.data.redis;

import org.springframework.util.CollectionUtils;

import java.util.Set;

public class SessionOperation {

    private RedisOperationsSessionRepository redisOperationsSessionRepository;

    public SessionOperation(RedisOperationsSessionRepository redisOperationsSessionRepository) {
        this.redisOperationsSessionRepository = redisOperationsSessionRepository;
    }

    public void loginSuccess(String sessionId, String otherSessionId) {
        RedisOperationsSessionRepository.RedisSession otherSession = redisOperationsSessionRepository.findById(otherSessionId);
        if (null == otherSession) {
            return;
        }
        RedisOperationsSessionRepository.RedisSession redisSession = redisOperationsSessionRepository.findById(sessionId);
        Set<String> attributeNames = otherSession.getAttributeNames();
        if (!CollectionUtils.isEmpty(attributeNames) && null != redisSession) {
            attributeNames.stream().forEach(attributeName -> {
                Object attribute = otherSession.getAttribute(attributeName);
                redisSession.setAttribute(attributeName, attribute);
            });
            redisOperationsSessionRepository.save(redisSession);
        }
    }
}